#include<iostream>
#include<string>
using namespace std;

class Solution {
public:
    //hello  qwe   qw
    void reserve_(string& str,int begin,int end)
    {
        while(begin<end)
        {
            char temp=str[begin];
            str[begin]=str[end];
            str[end]=temp;
            begin++;
            end--;
        }
    }
    string reverseWords(string s) 
    {
        //去掉后导空格
        int sz=s.size();
        while(s[sz-1]==' ')
        {
            sz--;
        }
        s.resize(sz);
        //去掉前导空格
        int begin=0;
        while(s[begin]==' ')
        {
            begin++;
        }
        for(int i=begin;i<s.size();i++)
        {
            s[i-begin]=s[i];
        }
        s.resize(sz-begin);
        //"Bob    Loves  Alice"
        //去掉中间多余空格，使用快慢指针
        int slow=1;
        int fast=1;
        while(fast<s.size())
        {
            if(s[slow]==s[slow-1]&&s[slow]==' ')
            {
                while(fast<s.size()&&s[fast]==' ')
                {
                    fast++;
                }
                s[slow]=s[fast];

            }
            else
            {
                s[slow]=s[fast];
                if(s[slow]==s[slow-1]&&s[slow]==' ')
                {

                }
                else
                {
                    slow++;
                    fast++;
                }
                
            }
        }
        s.resize(s.size()-(fast-slow));
        //整体反转
        reserve_(s,0,s.size()-1);
        //每个单词反转
        int right=0;
        int left=0;
        while((right=s.find(" ",left))!=string::npos)
        {
            reserve_(s,left,right-1);
            left=right+1;
        }
        reserve_(s,left,s.size()-1);
        return s;

    }
};